#!/usr/bin/env python
# -*- coding: utf8 -*-

import sys
import ConfigParser
import paramiko
import redis
import os

class INIT():
    def __init__(self):
        self.WorkDir = '/cihi/app'
        self.WorkDir_web = '/cihi/web/web'
        master = ConfigParser.ConfigParser()
        master.readfp(open(self.WorkDir+'/config/master.ini'))
        server = master.get('global','redis_server')
        port = master.get('global','redis_port')
        self.rds = redis.StrictRedis(host=server,port=int(port))
        self.gitserver = master.get('global','gitserver')
        self.checkinterval = master.get('global','checkinterval')
        self.contact = master.get('global','contact')
        self.notifyinterval = master.get('global','notifyinterval')
        self.notify = master.get('global','notify')

    def getSession(self,host):
        sshparam = self.rds.hgetall(host+'_att')
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            ssh.connect(host,int(sshparam.get('port')),sshparam.get('username'),sshparam.get('password'),timeout=3)
            sftp = ssh.open_sftp()
            err = ''
        except Exception,e:
            err = 'Connect to %s failed: %s' % (host,str(e))
            ssh,sftp = '',''
        return ssh,sftp,err
   
    def getClientList(self,mode='all'):
        if mode == 'ok':
            return self.rds.zrangebyscore('cihi_client','-inf','9999')
        elif mode == 'bad':
            return self.rds.zrangebyscore('cihi_client','10000','+inf')
        elif mode == 'noself':
            localiplist = os.popen("/sbin/ifconfig |grep -o 'inet addr:[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}'|cut -d':' -f2").read().split()
            iplist = self.rds.zrangebyscore('cihi_client','-inf','+inf')
            for ip in localiplist:
                try:
                    iplist.remove(ip)
                except:
                    pass
            return iplist
        else:
            return self.rds.zrangebyscore('cihi_client','-inf','+inf')
    
    def getProjectList(self):
        return self.rds.zrangebyscore('cihi_project','-inf','+inf')

    def getMonitorList(self,mode='all'):
        if mode == 'server':
            return self.rds.zrangebyscore('cihi_monitor','-inf','9999')
        elif mode == 'client':
            return self.rds.zrangebyscore('cihi_monitor','10000','+inf')
        else:
            return self.rds.zrangebyscore('cihi_monitor','-inf','+inf')

    def getProjectHavClient(self,project):
        result = self.rds.smembers(project+'_hostlist')
        return list(result)
   
    def getMonitorHavClient(self,monitor):
        result = self.rds.smembers(monitor+'_hostlist')
        return list(result)
   
    def getClientHavProject(self,host):
        result = []
        for project in self.getProjectList():
            if self.rds.sismember(project+'_hostlist',host):
                result.append(project)
        return result
    
    def getClientHavMonitor(self,host):
        result = []
        for monitor in self.getMonitorList():
            if self.rds.sismember(monitor+'_hostlist',host):
                result.append(monitor)
        return result

    def getProjectAtt(self,project):
        result = self.rds.hgetall(project+'_att')
        return result
   
    def getClientAtt(self,host):
        result = self.rds.hgetall(host+'_att')
        return result

    def getMonitorAtt(self,monitor):
        result = self.rds.hgetall(monitor+'_att')
        return result

    def getClientMonitor(self,host):
        result = self.rds.hgetall(host+'_monitor')
        if not result:
            return {}
        return result

    def saveHash(self,table,data):
        for key in data:
            self.rds.hset(table,key,data.get(key))
     
    def saveSet(self,table,data):
        self.rds.sadd(table,data)
   
    def delSet(self,table,data):
        self.rds.srem(table,data)
 
    def saveSSet(self,table,data,score=1):
        self.rds.zadd(table,score,data)

    def saveKey(self,key,data):
        self.rds.set(key,data)

    def getKey(self,key):
        return self.rds.get(key)

    def getHash(self,table,key='all'):
        if key == 'all':
            return self.rds.hgetall(table)
        else:
            return self.rds.hget(table,key)

    def delClient(self,host):
        self.rds.zrem('cihi_client',host)
        self.rds.delete(host+'_att')
        self.rds.delete(host+'_monitor')
        for project in self.getClientHavProject(host):
            self.rds.srem(project+'_hostlist',host)
        for monitor in self.getClientHavMonitor(host):
            self.rds.srem(monitor+'_hostlist',host)
    
    def delProject(self,project):
        self.rds.zrem('cihi_project',project)
        self.rds.delete(project+'_att')
        self.rds.delete(project+'_hostlist')

    def delMonitor(self,monitor):
        self.rds.zrem('cihi_monitor',monitor)
        self.rds.delete(monitor+'_att')
        self.rds.delete(monitor+'_hostlist')
